package com.xzh.mallorderapi.util;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.NonNull;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 功能：Spring工具类
 */
public class SpringUtils {
    private static ApplicationContext ac;
    private static ServletContext sc;

    //设置静态ApplicationContext实例
    public static void setApplicationContext(ApplicationContext applicationContext) {
        ac = applicationContext;
    }

    //获取spring上下文对象
    public static ApplicationContext getApplicationContext() {
        if (ac == null) {
            ServletContext sc = getServletContext();
            ac = WebApplicationContextUtils.findWebApplicationContext(sc);
        }
        return ac;
    }

    //设置静态ServletContext实例
    public static void setServletContext(ServletContext servletContext) {
        sc = servletContext;
    }

    //获取全局上下文对象
    public static ServletContext getServletContext() {
        if (sc == null) {
            sc = getServletRequest().getServletContext();
        }
        return sc;
    }

    //从本地线程变量中获取当前请求对象
    public static HttpServletRequest getServletRequest() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return sra.getRequest();
    }

    //从spring容器中获取单例实例
    public static <T> T getBean(@NonNull Class<T> clazz) {
        return ac.getBean(clazz);
    }
}
